from django import forms
from .models import *

import httplib2
import os
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
import datetime

def get_credentials():

	"""Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
	home_dir = os.path.expanduser('~')
	credential_dir = os.path.join(home_dir, '.credentials')
	if not os.path.exists(credential_dir):
	    os.makedirs(credential_dir)
	credential_path = os.path.join(credential_dir,
	                               'calendar-python-quickstart.json')

	store = oauth2client.file.Storage(credential_path)
	credentials = store.get()
	if not credentials or credentials.invalid:
	    flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
	    flow.user_agent = APPLICATION_NAME
	    if flags:
	        credentials = tools.run_flow(flow, store, flags)
	    else: # Needed only for compatibility with Python 2.6
	        credentials = tools.run(flow, store)
	    print('Storing credentials to ' + credential_path)
	return credentials


class createEventForm(forms.Form):
	summary = forms.CharField(label='Summary', max_length=100, required=True)
	location = forms.CharField(label='Location', initial='', required=False)
	description = forms.CharField(label='Description', widget=forms.Textarea, required=False)
	start = forms.CharField(label="Start", widget=forms.DateInput(format="%Y-%m-%d"), required=False)
	end = forms.CharField(label="End", widget=forms.DateInput(format="%Y-%m-%d"), required=False)
	timeZone = forms.CharField(label="Time Zone", initial='America/New York', required=False)

class getCalendarForm(forms.Form):
	choices = [(c.id, c.summary) for c in Calendar.objects.all()]

	calendarId = forms.ChoiceField(choices=choices, label='Select Calendar: ', initial='', required=True)

class getEventForm(forms.Form):
	choices = []

	def __init__(self, *args, **kwargs):
		super(self.__class__, self).__init__(*args, **kwargs)
		
		def find_events():
			credentials = get_credentials()
			http = credentials.authorize(httplib2.Http())
			service = discovery.build('calendar', 'v3', http=http)
			
			events = service.events().list(calendarId='l9am6s2f1j5b11cja3ipnv4djk@group.calendar.google.com').execute()
			events = list((event['id'],event['summary']) for event in events['items'])
			events.sort()
			return events
		events = find_events()
		# self.fields['eventID'].choices = events
		self.choices = events

	eventId = forms.ChoiceField(choices=choices, label='Select Event: ', initial='-------', widget=forms.Select(), required=True)
	

	